var login_register_layerno = null;
/**
 * 显示登录框
 * mode: 1显示登录框，2显示注册框， 3保持不变
 */
function tiosite_show_login(mode, title, onAfterCancel) {
	if (mode == 1) {
		layui.element.tabChange('login_reg', 'tiosite_layid_login');
	} else if (mode == 2){
		layui.element.tabChange('login_reg', 'tiosite_layid_reg');
	}

	var _h = 480;
	var _title = false;
	if (title) {
		_title = title;
		_h += 30;
	}

	login_register_layerno = layer.open({
		title: _title, //"登录 / 注册",
		type: 1, //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
		// area: ['400px', 'calc(100% - 45px)'],
		area: ['420px', _h + 'px'],
		content: $('#login_and_register'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
		// scrollbar: false,
		btn: null,
		// offset: 'rb',
		shade: 0.6,
		isOutAnim : false,

		// closeBtn: 0, //去掉右上角的按钮
		// shadeClose: true, //点击屏幕其它区域关闭弹窗

		// anim: 2,
		// maxmin: true,   //显示最大化和最小化
		success: function (layero, index) {

		},
		cancel: function (layero, index) {
			$('#login_and_register')[0].style.display = 'none';
			login_register_layerno = null;

			if (onAfterCancel) {
				onAfterCancel.call(onAfterCancel, layero, index);
			}
		}
	});
}

/**
 * 发起登录请求
 * @param {*} form 
 * @param {*} afterLoginSuccess 登录成功后，做一些事
 */
function tiosite_login(form, afterLoginSuccess) {

	if (!tt.validateForm('tiosite_loginForm')) {   //loginForm是form的name  
		return false;
	}

	var plainpwd = $.trim($('#tiosite_login_pwd_show').val()); //输入框的明文密码
	if (!plainpwd) {
		layer.alert("请输入密码");
		return;
	}
	var loginnamevalue = $.trim(form.loginname.value);
	form.loginname.value = loginnamevalue;

	var plainstr = '$' + '{' + loginnamevalue + '}' + plainpwd; //$和{分开写是因为freemarker冲突
	form.pd5.value = CryptoJS.MD5(CryptoJS.enc.Latin1.parse(plainstr)).toString();

	form.pwd.value = null;

	var data = $(form).serialize();
	if (login_register_layerno) {
		layer.close(login_register_layerno);
		login_register_layerno = null;
	}
	

	ajax.post('/login', {
		data: data,
		success: function (resp) {
			if (resp.ok == false) {
				if (resp.code == 3) {
					var aeskey = CryptoJS.enc.Utf8.parse(pwd_key_login_aes);
					var aespwd = aes_encrypt(plainpwd, aeskey); //aes加密后的密码
					form.pwd.value = aespwd;

					ajax.post('/login', {
						data: $(form).serialize(),
						success: function (resp2) {
							if (resp2.ok == false) {
								layer.msg(resp2.msg);
							} else if (resp2.ok) {
								after_login_success(resp2, afterLoginSuccess);
							}
						}
					});
				} else {
					if (resp.msg) {
						layer.msg(resp.msg);
					}
				}
			} else if (resp.ok) {
				//登录成功
				after_login_success(resp, afterLoginSuccess);
			}
		}
	});
}

/**
 * 登录成功后处理
 * @param {*} resp 
 */
function after_login_success(resp, afterLoginSuccess) {
	if (afterLoginSuccess) {
		afterLoginSuccess.call(afterLoginSuccess, resp);
		return;
	}

	var redirect = getQueryString('redirect_uri_after_login');
	if (redirect) {
		window.location.href = redirect;
	} else {
		// location.reload();
		var path = getRequestPath();
		if (path.startsWith('/login/') || path.startsWith('/email/')) {
			window.location.href = '/';
		} else {
			location.reload();
		}
	}
}

/**
 * 登录界面，密码框的回车事件
 * @param {*} evt
 * @param {*} form
 */
function pwdInputKeydowned(evt, form) {
	var evt = evt ? evt : window.event ? window.event : null; //兼容IE和FF
	if (evt.keyCode == 13) {
		tiosite_login(form);
	}
}

/**
 * 发起登出请求
 */
function tiosite_logout() {
	ajax.get('/logout', {
		// data: $(form).serialize(),
		success: function (data) {
			if (data.ok == false) {
				layer.msg(data.msg);
			} else if (data.ok) {
				// window.location.href = "/";
				location.reload();
			}
		}
	});
}

/**
 * 发起注册请求
 * @param {*} evt
 * @param {*} form1
 */
function tiosite_register(evt, form1) {

	if (!tt.validateForm('tiosite_regForm')) {   //loginForm是form的name  
		return false;
	}

	// var xx = $(form1).serialize();
	// alert(JSON.stringify(xx));
	var data = $(form1).serialize();
	if (login_register_layerno) {
		layer.close(login_register_layerno);
		login_register_layerno = null;
	}

	ajax.post('/register/1', {
		data: data,
		success: function (data) {
			if (data.ok == false) {
				layer.alert(data.msg);
			} else if (data.ok) {
				layer.alert(data.msg);
				// location.reload();
			}
		}
	});
}

$(function () {
	var element = layui.element;

	element.on('tab(login_reg)', function (data) {
		// console.log(data);
	});
	element.render();

	var form = layui.form;
	form.render();

	tt.Conf.errorStyle = 'alert';
	tt.Conf.clearOtherError = true;
	//给登录加js验证
	tt.vf.req.addId('tiosite_login_loginname', 'tiosite_login_pwd_show');
	tt.vf.email.addId("tiosite_login_loginname");

	//给注册加js验证
	tt.vf.req.addId('tiosite_reg_loginname', 'tiosite_reg_nick', 'tiosite_reg_pwd'/**, 'tiosite_reg_pwd2' */);
	tt.vf.email.addId("tiosite_reg_loginname");

	// var tiosite_reg_pwdField = new tt.Field('密码', null, 'tiosite_reg_pwd');
	// var tiosite_reg_pwd2Field = new tt.Field("确认密码", null, 'tiosite_reg_pwd2');
	// new tt.CV().add(tiosite_reg_pwd2Field).set('v', "==", tiosite_reg_pwdField);


});
